package com.team.childapp.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

/**
 * Create on: 9/14/21
 * by Mr.Zhu
 * Description: TODO
 */
public class JsonSerializer {

    private final static Gson g = new GsonBuilder().enableComplexMapKeySerialization().create();

    public JsonSerializer()
    {
    }

    public static <T> T deSerialize(String json, Class<T> rc)
    {
        T t = g.fromJson(json, rc);
        return t;
    }

    public static String serialize(Object o)
    {
        return g.toJson(o);
    }

    //解析讯飞json识别数据
    public static String parseIatResult(String json) {
        StringBuilder ret = new StringBuilder();
        try {
            JSONTokener tokener = new JSONTokener(json);
            JSONObject joResult = new JSONObject(tokener);

            JSONArray words = joResult.getJSONArray("ws");
            for (int i = 0; i < words.length(); i++) {
                // 转写结果词，默认使用第一个结果
                JSONArray items = words.getJSONObject(i).getJSONArray("cw");
                JSONObject obj = items.getJSONObject(0);
                ret.append(obj.getString("w"));
//				如果需要多候选结果，解析数组其他字段
//				for(int j = 0; j < items.length(); j++)
//				{
//					JSONObject obj = items.getJSONObject(j);
//					ret.append(obj.getString("w"));
//				}
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret.toString();
    }
}
